import type { Ref } from 'vue'

/**
 * 返回去重后的数组
 * @param arr 对象数组
 * @param getKey 去重key
 * @returns 去重后的数组
 */
export function duduplicateByKey<T, K extends string | number>(arr: T[], getKey: (item: T) => K): T[] {
  return arr.reduce<{ result: T[]; seen: Set<K> }>(
    (acc, currentItem) => {
      const key = getKey(currentItem)
      if (!acc.seen.has(key)) {
        acc.seen.add(key)
        acc.result.push(currentItem)
      }
      return acc
    },
    { result: [], seen: new Set<K>() } //初始值包含结果数组和已见集合
  ).result //最终返回结果数组
}
/**
 * 模拟进度条
 * @param start
 * @param end
 * @param duration
 * @param percentage
 */
export function simulateProgress(start: number, end: number, duration: number, percentage: Ref<number>) {
  let startTime: any = null
  function updateProgress() {
    if (!startTime) startTime = Date.now()
    const elasped = Date.now() - startTime
    const progress = Math.min(start + (end - start) * (elasped / duration), end)
    percentage.value = Number(progress.toFixed(0))
    if (progress < end) {
      requestAnimationFrame(updateProgress)
    }
  }
  requestAnimationFrame(updateProgress)
}
/**
 * 圆环进度条
 * @param finishdCount
 * @param sumCount
 * @param percentage
 */
export function simulateExtractProgress(finishdCount: number, sumCount: number, percentage: Ref<number>) {
  const start = Math.floor((finishdCount / sumCount) * 100)
  const end = Math.floor(((finishdCount + 1) / sumCount) * 100)
  if (start < percentage.value) return
  simulateProgress(start, end, 2 * 60 * 1000, percentage)
}
/**
 * 获取分页数据
 * @param data 原始数据
 * @param _page 当前页
 * @param _page_size 每页大小
 * @returns 分页后数据
 */
export function getPageData<T>(data: T[], _page: number, _page_size: number): T[] {
  return data.slice((_page - 1) * _page_size, _page * _page_size)
}
